
GateDefinition = {
	ports = {},
	logic = function(gate) end,
	input = function(gate, argv) end
}

function GateDefinition.new(objref, name, description, init, logic, input, global, ports)
	
	name = collapseescape(name)
	init  = collapseescape(init)
	logic = collapseescape(logic)
	input = collapseescape(input)
	global = collapseescape(global)
	description = collapseescape(description)
	
	local o = {
		objref = objref,
		name = name,
		description = description,
		ports = ports or {}
	}
	
	local initfunc = loadstring(tostring(init))
	if initfunc~=nil then
		o.init = initfunc() or function()end
	else
		print("Error loading init func for ".. (name or ""))
		print(init)
	end
	
	local logicfunc = loadstring(tostring(logic))
	if logicfunc ~= nil then
		o.logic = logicfunc() or function()end
	else
		print("Error loading logic function for " .. (name or ""))
		print(logic)
	end
	
	local inputfunc = loadstring(tostring(input))
	if inputfunc ~= nil then
		o.input = inputfunc() or function()end
	else
		print("Error loading input function for " .. (name or ""))
		print(input)
	end
	
	local globalfunc = loadstring(tostring(global))
	if globalfunc~=nil then
		globalfunc()
	else
		print("Error loading global function for ".. (name or ""))
		print(global)
	end
	
	return o
end

function GateDefinition.constructgate(def, objref, position, rotation)
	local gate = Gate.new(objref, def)

	for i = 1, #def.ports do
		local portd = def.ports[i]
		local type = portd.type
		local pos = {portd.position[1], portd.position[2], portd.position[3]}
		local dir = portd.direction

		if dir < 4 then
			dir = (dir + rotation) % 4
		end

		local x = pos[1]

		if rotation == 1 then
			pos[1] = pos[2]
			pos[2] = -x
		elseif rotation == 2 then
			pos[1] = -pos[1]
			pos[2] = -pos[2]
		elseif rotation == 3 then
			pos[1] = -pos[2]
			pos[2] = x
		end

		Gate.addport(gate, Port.new(type, dir, {position[1]+pos[1], position[2]+pos[2], position[3]+pos[3]}, portd.causeupdate, i))
	end

	return gate
end
